<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\model\Category;
use wechat\WxPay;

/**
 * 订单接口
 */
class Order extends Api
{

    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order();
    }

    //调起微信支付
    public function getpay()
    {
        $fee = $this->request->request('total_amount');
        $details = $this->request->request('details');
        $openid = $this->request->request('openid');
        $order_sn = $this->request->request('order_sn');

        $wxpay = new WxPay;
        $data = $wxpay->pay($openid, $fee, $details, $order_sn);
//        echo json_encode($data);
        $this->success('',$data);
    }

    //异步通知
    public function notify()
    {
        $xmlData = file_get_contents('php://input');

        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents('./logs/notify.php', json_encode($data).PHP_EOL, FILE_APPEND);


        ksort($data);
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != 'sign') {
                $buff .= $k . '=' . $v . '&';
            }
        }
        $stringSignTemp = $buff . 'key=OxTamUkf8tgFVwhOBbzCsduszC4fEMjL';//key为证书密钥,商户key
        $sign = strtoupper(md5($stringSignTemp));
        //判断算出的签名和通知信息的签名是否一致
        if ($sign == $data['sign']) {
            //修改订单状态
            // $this->updateOrderStatus($data['out_trade_no']);
            update_pay_status($data['out_trade_no']);


            //处理完成之后，告诉微信成功结果
            echo '<xml>
                      <return_code><![CDATA[SUCCESS]]></return_code>
                      <return_msg><![CDATA[OK]]></return_msg>
                  </xml>';
            exit();
        } else {
            file_put_contents('./logs/notify.php', 'notify签名错误'.PHP_EOL, FILE_APPEND);

        }
    }

    public function goodsbuy(){
        $goods_id = $this->request->request('goods_id/d');
        $type = $this->request->request('type',1);//类型:0=买断,1=买一条
        $goods = \app\common\model\Goods::get($goods_id);
        if(!$goods){
            $this->error('商品不存在');
        }
        $type == 1 ? $goods_num = 1 : $goods_num = $goods['total_num'];
        $account = rand($goods['price']*$goods_num,2);

        $user = \app\common\model\User::get($this->auth->id);
        if($account*100 - $user['score']*100 > 0){
            $this->error('余额不足,请充值','',2);
        }

        $params = [
            'order_sn' => date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
            'user_id' => $this->auth->id,
            'goods_id' => $goods_id,
            'goods_price' => $goods['price'],
            'goods_num' =>$goods_num,
            'account' => $account
        ];

        $result = $this->model->save($params);
        if($result){
            $this->success('购买成功');
        }else{
            $this->error('购买失败');
        }
    }

    public function myorder(){

        $data = Db::name('order')->alias('o')
            ->join('goods g','g.id = o.goods_id','LEFT')
            ->where('o.user_id',$this->auth->id)
            ->order('id desc')
            ->field('g.id,g.title,o.createtime,o.account,g.description')
            ->select();
        $this->success('',$data);
    }



}